﻿using System;
using System.Net;

namespace FBGraph.Async
{
    internal class FBGraphAsyncRequest<TResult> : FBGraphApiRequest, IFBGraphAsyncRequest
        where TResult : IFBGraphResult
    {
        public event FBGraphAsyncErrorHandler Error;

        public FBGraphAsyncRequest(FBGraphApiRequest request, TResult result)
            : base(request.InnerRequest)
        {
            this.Result = result;
        }

        public IFBGraphAsyncRequest Dependency { get; set; }
        public Boolean IsCompleted { get; set; }
        public Exception Exception { get; set; }

        public Type ReturnType { get { return typeof(TResult); } }

        public TResult Result { get; internal set; }
        IFBGraphResult IFBGraphAsyncRequest.Result
        {
            get { return (IFBGraphResult)this.Result; }
            set
            {
                if (value is TResult) this.Result = (TResult)value;
            }
        }

        public Action<Object> Callback { get; set; }

        public FBGraphAsyncRequest<TResult> WaitFor(IFBGraphAsyncRequest dependency)
        {
            this.Dependency = dependency;
            return this;
        }

        void IFBGraphAsyncRequest.OnError(FBGraphAsyncErrorEventArgs e)
        {
            if (this.Error != null) this.Error(this, e);
        }
    }
}